package com.hsd.controller;

import com.hsd.constant.ErrorConstant;
import com.hsd.pojo.Result;
import com.hsd.service.RadixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @ Author：YangYu
 * @ Package：com.hsd.controller
 * @ Project：hsd_calculator
 * @ Description: 二进制与十进制的相互转换
 * @ Date：2025/4/13  16:18
 */
@RestController
@RequestMapping("/calculate/radix")
@Slf4j
public class RadixController {

    @Autowired
    private RadixService radixService;

    /**
     * 二进制转十进制
     * @param request
     * @return
     */
    @PostMapping("/toten")
    public Result binaryToDecimal(@RequestBody Map<String, String> request) {
        // 获取二进制数
        String binary = request.get("num");

        // 验证二进制字符串是否合法
        if (!binary.matches("[01]+")) {
            return Result.error(ErrorConstant.PARAM_ERROR);
        }
        log.info("二进制转十进制：{} ", binary);

        // 将二进制字符串转换为十进制整数
        int decimal = radixService.toten(binary);

        return Result.success(decimal);
    }

    /**
     * 十进制转二进制
     * @param request
     * @return
     */
    @PostMapping("/totwo")
    public Result DecimalToBinary(@RequestBody Map<String, String> request) {
        // 获取十进制数
        String decimal = request.get("num");

        log.info("十进制转二进制：{} ", decimal);

        // 将十进制字符串转换为二进制整数
        String binary = radixService.totwo(decimal);

        return Result.success(binary);
    }


}
